package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {


    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private  HttpServletRequest request;

    @PostMapping("/login")
    public R loginEmp(@RequestBody Employee emp) {

        //密码md5加密
        String pwd = emp.getPassword();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(pwd.getBytes());

        //根据用户名查询数据库
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        qw.lambda().eq(true,Employee::getUsername,emp.getUsername());
        Employee employee = employeeService.getOne(qw);

        if (null == employee || "".equals(employee.getUsername())) {
            //返回登录失败
            return R.error("登录失败！用户名或密码错误");
        }

        //密码比对是否一致
        if (!(employee.getPassword().equals(md5DigestAsHex))) {
            //返回登录失败
            return R.error("登录失败！密码错误❌");
        }

        //查看员工状态是否被禁用
        if (1 != employee.getStatus()) {
            //员工状态已被禁用
            return R.error("抱歉！该员工状态为已禁用.");
        }

        //程序没有执行其它分支返回 说明登录成功!
        HttpSession session = request.getSession();
        session.setAttribute("employee",employee.getId());
        // R<String> stringR = new R<>(1, "欢迎进入瑞吉内卖(*^_^*)!!", null);
        // stringR.add("name","尊敬的甲方爸爸");
        session.setAttribute("userInfo",employee);

        return R.success(employee);
        // return stringR;
    }

    @PostMapping("/logout")
    public R logOut() {
        // request.getSession().removeAttribute("employee");
        request.getSession().invalidate();
        return R.success("系统退出成功");
    }

    @PostMapping
    public R save(@RequestBody Employee employee,@Autowired HttpSession session) {

        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee empOne = employeeService.getOne(wrapper);
        if (null != empOne) {
            throw new CustomException("用户名称"+employee.getUsername()+"已经存在.");
        }


        //新增的员工默认密码为123456
        String pwd = "123456";
        //使用MD5密钥对传入的password参数进行加密处理
        String password = DigestUtils.md5DigestAsHex(pwd.getBytes());
        employee.setPassword(password);
        employee.setId(BigInteger.valueOf(Math.abs(UUID.randomUUID().hashCode())));
        log.info("Emp员工信息[{}]",employee);
        /*
        //封装创建时间
        employee.setCreateTime(LocalDateTime.now());
        //封装修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //创建人 以及 修改人信息
        Employee userInfo =(Employee)session.getAttribute("userInfo");

        employee.setCreateUser(userInfo.getId().longValue());
        employee.setUpdateUser(userInfo.getId().longValue());
        */
        boolean result = employeeService.save(employee);

        if (result) {
            return R.success("新增员工成功!!!");
        } else {
            return R.error("失败....");
        }
    }

    @GetMapping("/page2")
    public R<Page> getEmployeePage(@RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "10") Integer pageSize, String name) {
        log.info("正在处理分页查询请求...页数:{},每页显示:{},{}",page,pageSize,name);

        List<Employee> pageEmps = employeeService.pageEmps(page, pageSize, name);

        Page<Employee> objectPage = new Page<>();
        objectPage.setRecords(pageEmps);
        objectPage.setCurrent(objectPage.getSize());


        return R.success(objectPage);
    }


    @GetMapping("/page")
    public R<Page> queryEmployeeInformationByPage(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer pageSize,String name) {

        Page<Employee> empPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        // qw.like(name != null,Employee::getName,name);
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        qw.orderByDesc(Employee::getUpdateTime);
        Page<Employee> employeePage = employeeService.page(empPage, qw);
        R<Page> objectR = R.success(employeePage);
        return objectR;
    }

    @PutMapping
    public R<String> modifyEmployeeStatus(@RequestBody Employee emp,HttpServletRequest request) {
        log.info("修改前的用户ID:{},status:{}",emp.getId(),emp.getStatus());

        if (!ObjectUtils.isNotNull(emp)) {
            throw new NullPointerException("数据为空.");
        }

        //获取注入的username属性 若不为null则表示不是修改状态而是 新增操作
        String username = emp.getUsername();
        if (username != null) {

            LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Employee::getUsername,username);
            wrapper.ne(Employee::getId,emp.getId());
            int count = employeeService.count(wrapper);
            if (count > 0) {
                //能够查询出数据说明存在id迥异用户名却相同的data
                throw new CustomException("error!存在相同用户名");
            }

        }

        //获取登录信息中的userID
        // Employee employee = (Employee) request.getSession().getAttribute("userInfo");
        if (emp.getStatus() == 1) {
            //启用
            emp.setStatus(0);
        }else if (emp.getStatus() == 0) {
            //禁用
            emp.setStatus(1);
        }
        /*
        //设置修改员工信息的更新时间
        emp.setUpdateTime(LocalDateTime.now());
        //设置修改员工信息的操作人id
        emp.setUpdateUser(employee.getId().longValue());
         */

        boolean result = employeeService.updateById(emp);
        if (result) {
            return R.success("修改员工数据成功!");
        }
        return R.error("修改失败..");
    }

    /**
     * 根据员工id查询出数据回显在修改页面框
     */
    @GetMapping("/{id}")
    public R findEmpById(@PathVariable String id) {
        BigDecimal reqId = new BigDecimal(id);
        if (reqId != null && reqId != BigDecimal.valueOf(0)) {
            Employee empById = employeeService.getById(reqId);
            if (null != empById && !"".equals(empById.toString())) {
                return R.success(empById);
            }
            return R.error("没有查询到相关员工信息..");
        }
        return R.error("请确认当前员工id值后再重试..");
    }

    /**
     * 修改员工数据
     */

    @PutMapping("/update")
    public R modifyEmployeeData(@RequestBody Employee emp) {

        if (ObjectUtils.isNotNull(emp)) {
            throw new NullPointerException("数据为空.");
        }
        Employee employee = (Employee) request.getSession().getAttribute("userInfo");

        emp.setUpdateTime(LocalDateTime.now());            //设置修改数据更新时间
        emp.setUpdateUser(employee.getUpdateUser());    //设置修改人数据
        boolean result = employeeService.updateById(emp);
        if (result) {
            return R.success("修改员工数据成功!");
        }
        return R.error("修改失败..");
    }
}
